<template>
  <div class="md-container">
    <div class="editor-section">
      <div class="toastui-editor-defaultUI-toolbar">
        <div class="toastui-editor-toolbar-group">
          <button type="button" class="heading toastui-editor-toolbar-icons active" aria-label="Headings" @click="handleToolbarClick('heading')"></button>
          <button type="button" class="bold toastui-editor-toolbar-icons" aria-label="Bold" @click="handleToolbarClick('bold')"></button>
          <button type="button" class="italic toastui-editor-toolbar-icons" aria-label="Italic" @click="handleToolbarClick('italic')"></button>
          <button type="button" class="strike toastui-editor-toolbar-icons" aria-label="Strike" @click="handleToolbarClick('strike')"></button>
          <div class="toastui-editor-toolbar-divider"></div>
        </div>
        <div class="toastui-editor-toolbar-group">
          <button type="button" class="hrline toastui-editor-toolbar-icons" aria-label="Line" @click="handleToolbarClick('hrline')"></button>
          <button type="button" class="quote toastui-editor-toolbar-icons" aria-label="Blockquote" @click="handleToolbarClick('quote')"></button>
          <div class="toastui-editor-toolbar-divider"></div>
        </div>
        <div class="toastui-editor-toolbar-group">
          <button type="button" class="bullet-list toastui-editor-toolbar-icons" aria-label="Unordered list" @click="handleToolbarClick('bullet-list')"></button>
          <button type="button" class="ordered-list toastui-editor-toolbar-icons" aria-label="Ordered list" @click="handleToolbarClick('ordered-list')"></button>
          <button type="button" class="task-list toastui-editor-toolbar-icons" aria-label="Task" @click="handleToolbarClick('task-list')"></button>
          <button type="button" class="indent toastui-editor-toolbar-icons" aria-label="Indent" disabled="true"></button>
          <button type="button" class="outdent toastui-editor-toolbar-icons" aria-label="Outdent" disabled="true"></button>
          <div class="toastui-editor-toolbar-divider"></div>
        </div>
        <div class="toastui-editor-toolbar-group">
          <button type="button" class="table toastui-editor-toolbar-icons" aria-label="Insert table" @click="handleToolbarClick('table')"></button>
          <button type="button" class="image toastui-editor-toolbar-icons" aria-label="Insert image" @click="handleToolbarClick('image')"></button>
          <button type="button" class="link toastui-editor-toolbar-icons" aria-label="Insert link" @click="handleToolbarClick('link')"></button>
          <div class="toastui-editor-toolbar-divider"></div>
        </div>
        <div class="toastui-editor-toolbar-group">
          <button type="button" class="code toastui-editor-toolbar-icons" aria-label="Inline code" @click="handleToolbarClick('code')"></button>
          <button type="button" class="codeblock toastui-editor-toolbar-icons" aria-label="Insert codeBlock" @click="handleToolbarClick('codeblock')"></button>
          <div class="toastui-editor-toolbar-divider"></div>
        </div>
        <div class="toastui-editor-toolbar-group">
          <div class="toastui-editor-toolbar-item-wrapper" style="display: inline-block;">
            <label class="scroll-sync active"><input type="checkbox"><span class="switch"></span></label>
          </div>
          <div class="toastui-editor-toolbar-divider" style="display: none;"></div>
        </div>
        <div class="toastui-editor-toolbar-group" style="display: none;">
          <button type="button" class="more toastui-editor-toolbar-icons"></button>
          <div class="toastui-editor-dropdown-toolbar" style="display: none;"></div>
        </div>
        <div class="toastui-editor-tooltip" style="display: none; left: 724px; top: 45px;">
          <div class="arrow"></div>
          <span class="text">Inline code</span>
        </div>
      </div>
      <Editor
          v-model="markdownInput"
          class="markdown-input"
          ref="editorRef"
          :scroll-percent="editorScrollPercent"
          @scroll="handleEditorScroll"
        />
    </div>
   
    <div class="preview-section">
      <PreView 
        :markdown="markdownInput" 
        ref="previewRef"
        :scroll-percent="previewScrollPercent"
        @scroll="handlePreviewScroll"
      ></PreView>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Editor from './components/Editor.vue'
import PreView from './components/PreView.vue'

const markdownInput = ref('')
const editorRef = ref(null)
const previewRef = ref(null)
const editorScrollPercent = ref(0)
const previewScrollPercent = ref(0)

// 工具栏按钮点击处理函数
const handleToolbarClick = (action) => {
  console.log('handleToolbarClick', !editorRef.value, editorRef.value)
  if (!editorRef.value || !editorRef.value.editorView) return
  
  const editorView = editorRef.value.editorView
  const selection = editorView.state.selection.main
  const from = selection.from
  const to = selection.to
  const selectedText = editorView.state.doc.sliceString(from, to)
  
  let insertText = ''
  let newCursorPos = from
  
  switch (action) {
    case 'heading':
      insertText = selectedText ? `# ${selectedText}` : '# '
      newCursorPos = from + (selectedText ? 2 : 2)
      break
    case 'bold':
      insertText = selectedText ? `**${selectedText}**` : '****'
      newCursorPos = from + (selectedText ? 2 : 2)
      break
    case 'italic':
      insertText = selectedText ? `*${selectedText}*` : '**'
      newCursorPos = from + (selectedText ? 1 : 1)
      break
    case 'strike':
      insertText = selectedText ? `~~${selectedText}~~` : '~~~~'
      newCursorPos = from + (selectedText ? 2 : 2)
      break
    case 'hrline':
      insertText = `
---
`
      newCursorPos = from + 5
      break
    case 'quote':
      insertText = selectedText ? `> ${selectedText}` : '> '
      newCursorPos = from + (selectedText ? 2 : 2)
      break
    case 'bullet-list':
      insertText = selectedText ? `- ${selectedText}` : '- '
      newCursorPos = from + (selectedText ? 2 : 2)
      break
      case 'ordered-list':
        insertText = selectedText ? `1. ${selectedText}` : '1. '
        newCursorPos = from + (selectedText ? 3 : 3)
        break
      case 'task-list':
        insertText = selectedText ? `- [ ] ${selectedText}` : '- [ ] '
        newCursorPos = from + (selectedText ? 6 : 6)
        break
      case 'table':
        insertText = `
| Header 1 | Header 2 | Header 3 |
|----------|----------|----------|
| Cell 1   | Cell 2   | Cell 3   |
| Cell 4   | Cell 5   | Cell 6   |
`
        newCursorPos = from + 10
        break
      case 'image':
        insertText = '![alt text](image-url)'
        newCursorPos = from + 12
        break
      case 'link':
        insertText = selectedText ? `[${selectedText}](url)` : '[](url)'
        newCursorPos = from + (selectedText ? selectedText.length + 3 : 1)
        break
      case 'code':
        insertText = selectedText ? `\`${selectedText}\`` : '``'
        newCursorPos = from + (selectedText ? 1 : 1)
        break
      case 'codeblock':
        insertText = selectedText ? `\`\`\`
${selectedText}
\`\`\`` : '```\n\n```'
        newCursorPos = from + (selectedText ? 4 : 4)
        break
      default:
        return
    }
    console.log('insertText', insertText)
    console.log('newCursorPos', newCursorPos)
    // 更新文本内容
    // 使用 CodeMirror 的 transaction 来更新内容
    editorView.dispatch({
      changes: {
        from: from,
        to: to,
        insert: insertText
      },
      selection: {
        anchor: newCursorPos,
        head: newCursorPos
      }
    })
    
    // 聚焦编辑器
    editorView.focus()
  }

// 设置默认内容
const defaultMarkdown = `# 欢迎使用 Markdown 编辑器

这是一个功能强大的编辑器，支持各种 Markdown 语法。

## 主要特性

- **所见即所得** - 实时预览编辑效果
- **代码高亮** - 支持多种编程语言
- **表格支持** - 轻松创建数据表格
- **LaTeX 公式** - 支持数学公式编辑
- **Mermaid 图表** - 创建流程图和序列图

## 代码示例

\`\`\`javascript
// JavaScript 示例
function greet(name) {
    console.log(\`Hello, \${name}!\`);
}

greet('Markdown 用户');
\`\`\`

\`\`\`python
def greet(name):
    print(f"Hello, {name}!")
greet("Markdown 用户")
\`\`\`

\`\`\`c
#include <stdio.h>
int main() {
    printf("Hello, World!");
    return 0;
}  
\`\`\`

\`\`\`go
package main
import "fmt"
func main() {
    fmt.Println("Hello, World!")
}
\`\`\`

\`\`\`shell
echo "Hello, World!"
\`\`\`

\`\`\`dart
void main() {
    print('Hello, World!');
}
\`\`\`

\`\`\`nginx
server {
    listen 80;
    server_name example.com;    
    location / {
        proxy_pass http://backend;
    }
}
\`\`\`

## 数学公式示例

$$
\begin{aligned}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{aligned}
$$

## 表格示例

| 功能         | 是否支持 | 说明         |
|--------------|----------|--------------|
| 图片上传     | ✓        | 支持拖放上传 |
| 深色模式     | ✓        | 夜间友好     |
| 导出 HTML    | ✓        | 完整格式保留 |
| 版本历史     | ✓        | 自动保存记录 |

## Mermaid 流程图

\`\`\`mermaid
graph TD;
    A[开始] --> B(编辑内容);
    B --> C{是否满意?};
    C -->|是| D[保存内容];
    C -->|否| B;
    D --> E[完成];
\`\`\`
`

// 处理编辑器滚动事件
const handleEditorScroll = (percent) => {
  editorScrollPercent.value = percent
  previewScrollPercent.value = percent
}

// 处理预览区域滚动事件
const handlePreviewScroll = (percent) => {
  previewScrollPercent.value = percent
  editorScrollPercent.value = percent
}

// 组件挂载时设置默认值
onMounted(() => {
  markdownInput.value = defaultMarkdown
})

</script>

<style scoped>
.md-container {
  display: flex;
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.editor-section {
  flex: 1;
  border-right: 1px solid #ddd;
  height: 100vh;
  width: 50%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.preview-section {
  flex: 1;
  height: 100vh;
  width: 50%;
  overflow: auto;
}

/* Toast UI Editor 工具栏样式 */
.toastui-editor-defaultUI-toolbar {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  padding: 8px 12px;
  min-height: 44px;
  flex-wrap: wrap;
}

.toastui-editor-toolbar-group {
  display: flex;
  align-items: center;
  margin-right: 8px;
}

.toastui-editor-toolbar-divider {
  width: 1px;
  height: 20px;
  background: #dee2e6;
  margin: 0 8px;
}

.toastui-editor-toolbar-icons {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 2px;
  position: relative;
}

.toastui-editor-toolbar-icons:hover {
  background: #e9ecef;
}

.toastui-editor-toolbar-icons:active {
  background: #dee2e6;
}

.toastui-editor-toolbar-icons:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 工具栏图标内容（使用伪元素显示图标） */
.toastui-editor-toolbar-icons.heading::before {
  content: "H";
  font-weight: bold;
  font-size: 14px;
}

.toastui-editor-toolbar-icons.bold::before {
  content: "B";
  font-weight: bold;
  font-size: 14px;
}

.toastui-editor-toolbar-icons.italic::before {
  content: "I";
  font-style: italic;
  font-size: 14px;
}

.toastui-editor-toolbar-icons.strike::before {
  content: "S";
  text-decoration: line-through;
  font-size: 14px;
}

.toastui-editor-toolbar-icons.hrline::before {
  content: "—";
  font-size: 16px;
  font-weight: bold;
}

.toastui-editor-toolbar-icons.quote::before {
  content: "❝";
  font-size: 14px;
}

.toastui-editor-toolbar-icons.bullet-list::before {
  content: "•";
  font-size: 18px;
}

.toastui-editor-toolbar-icons.ordered-list::before {
  content: "1.";
  font-size: 14px;
}

.toastui-editor-toolbar-icons.task-list::before {
  content: "☐";
  font-size: 14px;
}

.toastui-editor-toolbar-icons.indent::before {
  content: "→";
  font-size: 14px;
}

.toastui-editor-toolbar-icons.outdent::before {
  content: "←";
  font-size: 14px;
}

.toastui-editor-toolbar-icons.table::before {
  content: "⊞";
  font-size: 14px;
}

.toastui-editor-toolbar-icons.image::before {
  content: "🖼";
  font-size: 12px;
}

.toastui-editor-toolbar-icons.link::before {
  content: "🔗";
  font-size: 12px;
}

.toastui-editor-toolbar-icons.code::before {
  content: "{ }";
  font-size: 12px;
  font-family: monospace;
}

.toastui-editor-toolbar-icons.codeblock::before {
  content: "```";
  font-size: 10px;
  font-family: monospace;
}

.toastui-editor-toolbar-icons.more::before {
  content: "⋯";
  font-size: 16px;
  font-weight: bold;
}

/* 滚动同步开关样式 */
.scroll-sync {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 12px;
  color: #495057;
}

.scroll-sync input {
  margin-right: 4px;
}

.scroll-sync.active {
  color: #007bff;
}

.markdown-input {
  flex: 1;
  height: calc(100vh - 60px);
}



</style>
